package aes.client;

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.*;

import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;

import common.*;

public class AddQuestionToExamUI extends JPanel implements ActionListener, ListSelectionListener, Observer {

	/**
	 * 
	 */
	private static final long serialVersionUID = -9159991715916781510L;
	
	private ClientUI ui;
	private Client c;
	private int eId = 0;
	
	private JButton btnCancel;
	private JButton btnAdd;
	private JTable table;
	private JTextField txtPoints;
	
	/**
	 * Constructor
	 * @param c Client object
	 * @param ui ClientUI object
	 */
	public AddQuestionToExamUI(Client c,ClientUI ui) {
		super();
		this.c = c;
		this.ui = ui;
		JFrame frame = new JFrame();
		frame.setSize(640, 480);
		frame.add(this);
		
		c.addObserver(this);
		setLayout(new GridBagLayout());

		JPanel panel = new JPanel();
		panel.setBorder(new LineBorder(new Color(0, 0, 0), 2, true));
		panel.setPreferredSize(new Dimension(600,400));

		GridBagConstraints gbc_panel = new GridBagConstraints();
		gbc_panel.insets = new Insets(5, 0, 5, 0);
		gbc_panel.gridx = 0;
		gbc_panel.gridy = 0;
		add(panel,gbc_panel);
		GridBagLayout gbl_panel = new GridBagLayout();
		gbl_panel.rowWeights = new double[]{0.0, 1.0, 0.0, 0.0};
		gbl_panel.columnWeights = new double[]{0.0, 1.0, 0.0};
		panel.setLayout(gbl_panel);

		JLabel lblAesTitle = new JLabel("Add Question to Exam");
		lblAesTitle.setVerticalAlignment(SwingConstants.TOP);
		lblAesTitle.setHorizontalAlignment(SwingConstants.CENTER);
		lblAesTitle.setBounds(7, 10, 70, 17);
		lblAesTitle.setFont(new Font("Tahoma", Font.BOLD, 14));

		GridBagConstraints gbc_lblAesTitle = new GridBagConstraints();
		gbc_lblAesTitle.anchor = GridBagConstraints.NORTH;
		gbc_lblAesTitle.gridwidth = 3;
		gbc_lblAesTitle.fill = GridBagConstraints.BOTH;
		gbc_lblAesTitle.insets = new Insets(5, 0, 5, 0);
		gbc_lblAesTitle.gridx = 0;
		gbc_lblAesTitle.gridy = 0;
		panel.add(lblAesTitle, gbc_lblAesTitle);
		
		JLabel lblAvaliableQuestions = new JLabel("Avaliable Questions:");
		GridBagConstraints gbc_lblAvaliableQuestions = new GridBagConstraints();
		gbc_lblAvaliableQuestions.anchor = GridBagConstraints.NORTHEAST;
		gbc_lblAvaliableQuestions.insets = new Insets(0, 5, 5, 5);
		gbc_lblAvaliableQuestions.gridx = 0;
		gbc_lblAvaliableQuestions.gridy = 1;
		panel.add(lblAvaliableQuestions, gbc_lblAvaliableQuestions);
		
		table = new JTable(){
			/**
			 * 
			 */
			private static final long serialVersionUID = 7458975972801695617L;

			public boolean isCellEditable(int rowIndex, int colIndex) {
				return false; //Disallow the editing of any cell
			}};
			table.setModel(new DefaultTableModel(
					new Object[][] {
					},
					new String[] {
							"Question #", "Question", "ID"
					}
					) {
				/**
				 * 
				 */
				private static final long serialVersionUID = -4567261985989300298L;
				@SuppressWarnings("rawtypes")
				Class[] columnTypes = new Class[] {
					String.class, String.class, String.class 
				};
				@SuppressWarnings({ "unchecked", "rawtypes" })
				public Class getColumnClass(int columnIndex) {
					return columnTypes[columnIndex];
				}
			});
		table.removeColumn(table.getColumnModel().getColumn(2));
		JScrollPane scrollPane = new JScrollPane(table);
		table.setFillsViewportHeight(true);
		table.getSelectionModel().addListSelectionListener(this);
		GridBagConstraints gbc_table = new GridBagConstraints();
		gbc_table.insets = new Insets(0, 0, 5, 5);
		gbc_table.fill = GridBagConstraints.BOTH;
		gbc_table.gridx = 1;
		gbc_table.gridy = 1;
		panel.add(scrollPane, gbc_table);
		
		JLabel lblPoints = new JLabel("Points:");
		GridBagConstraints gbc_lblPoints = new GridBagConstraints();
		gbc_lblPoints.anchor = GridBagConstraints.EAST;
		gbc_lblPoints.insets = new Insets(0, 5, 5, 5);
		gbc_lblPoints.gridx = 0;
		gbc_lblPoints.gridy = 2;
		panel.add(lblPoints, gbc_lblPoints);
		
		txtPoints = new JTextField();
		GridBagConstraints gbc_txtPoints = new GridBagConstraints();
		gbc_txtPoints.anchor = GridBagConstraints.NORTH;
		gbc_txtPoints.insets = new Insets(0, 0, 5, 5);
		gbc_txtPoints.fill = GridBagConstraints.HORIZONTAL;
		gbc_txtPoints.gridx = 1;
		gbc_txtPoints.gridy = 2;
		panel.add(txtPoints, gbc_txtPoints);
		txtPoints.setColumns(10);
		
		btnAdd = new JButton("Add", new ImageIcon(ExamEditorUI.class.getResource("/aes/client/images/Save.png")));
		btnAdd.addActionListener(this); 
		GridBagConstraints gbc_btnAdd = new GridBagConstraints();
		gbc_btnAdd.insets = new Insets(5, 5, 5, 5);
		gbc_btnAdd.gridx = 0;
		gbc_btnAdd.gridy = 3;
		panel.add(btnAdd, gbc_btnAdd);
		btnAdd.setBounds(353, 7, 57, 23);
		
		btnCancel = new JButton("Cancel", new ImageIcon(ExamEditorUI.class.getResource("/aes/client/images/Cancel.png")));
		btnCancel.setHorizontalAlignment(SwingConstants.LEFT);
		btnCancel.addActionListener(this); 
		
		GridBagConstraints gbc_btnCancel = new GridBagConstraints();
		gbc_btnCancel.gridwidth = 2;
		gbc_btnCancel.anchor = GridBagConstraints.WEST;
		gbc_btnCancel.insets = new Insets(5, 0, 5, 5);
		gbc_btnCancel.gridx = 1;
		gbc_btnCancel.gridy = 3;
		panel.add(btnCancel, gbc_btnCancel);
		btnCancel.setBounds(353, 7, 57, 23);
	}
	
	/**
	 * Question ID setter
	 * @param id Question ID
	 */
	public void setExamID(int id){
		eId=id;
		// Load questions list.
		CommandMessage msg = new CommandMessage(CommandMessage.GET_EXAM_NOT_EXISTENT_QUESTIONS, new String[]{Integer.toString(eId)});
		try {
			c.sendToServer(msg);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	@SuppressWarnings("static-access")
	@Override
	public void update(Observable arg0, Object arg1) {
		if (arg1 instanceof CommandMessage) {
			CommandMessage ms=(CommandMessage)arg1;
			if (ms.getCommand().equals(CommandMessage.ACKNOWLEDGE_MESSAGE) && ((String)ms.getParams()[0]).equals(CommandMessage.GET_EXAM_NOT_EXISTENT_QUESTIONS)) {
				if (ms.getParams().length < 2)
				{
					// Go back.
					c.deleteObserver(this);
					ui.SetContent(ui.EXAMS_EDITOR_SCREEN);
					ExamEditorUI panel= ((ExamEditorUI)ui.getContentPane());
					panel.setExamID(eId);
				}
				Question[] questions = (Question[]) ms.getParams()[1];
				DefaultTableModel model =(DefaultTableModel) table.getModel();
				model.setRowCount(0);
				for (Question q: questions) {
					String[] row = new String[3];
					row[0] = String.format("%03d", q.getQuestionID());
					row[1] = q.getQuestion();
					row[2] = Integer.toString(q.getId());
					model.addRow(row);
				}
				table.setModel(model);
			}
			else if (ms.getCommand().equals(CommandMessage.ACKNOWLEDGE_MESSAGE) && ((String)ms.getParams()[0]).equals(CommandMessage.ADD_QUESTION_TO_EXAM)) {
				if (ms.getParams().length < 4) {
					ui.ShowMessageBox("ERROR", "Can't add question", JOptionPane.ERROR_MESSAGE);
					return;
				}
				ui.ShowMessageBox("Message", "Question was added", JOptionPane.INFORMATION_MESSAGE);
				txtPoints.setText("");
				setExamID(eId);
			}
		}
	}

	@Override
	public void valueChanged(ListSelectionEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@SuppressWarnings("static-access")
	@Override
	public void actionPerformed(ActionEvent arg0) {
		if (arg0.getSource().equals(btnCancel)) {
			// Back.
			c.deleteObserver(this);
			ui.SetContent(ui.EXAMS_EDITOR_SCREEN);
			ExamEditorUI panel= ((ExamEditorUI)ui.getContentPane());
			panel.setExamID(eId);
		}
		else if (arg0.getSource().equals(btnAdd))  {
			// Add question.
			if (!checkValues())
				return;
			DefaultTableModel model =(DefaultTableModel) table.getModel();
			Vector<?> o1 = (Vector<?>) model.getDataVector().get(table.getSelectedRow());
			int id = Integer.parseInt((String)o1.get(2));
			Question q = new Question();
			q.setId(id);
			q.setPoints(Integer.parseInt(txtPoints.getText()));
			CommandMessage msg = new CommandMessage(CommandMessage.ADD_QUESTION_TO_EXAM, new Object[]{Integer.toString(eId), q});
			try {
				c.sendToServer(msg);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
	
	/**
	 * Validates input fields
	 * @return Validation result
	 */
	@SuppressWarnings({ "static-access" })
	private boolean checkValues() {
		if(txtPoints.getText().trim().equals("")){
			ui.ShowMessageBox("ERROR", "Please fill all required fields", JOptionPane.ERROR_MESSAGE);
			return false;
		}
		int input;
		try {  
			input=Integer.parseInt( txtPoints.getText() );  
		}  
		catch( Exception ex) {  
			ui.ShowMessageBox("ERROR", "Points field number must be numeric", JOptionPane.ERROR_MESSAGE);
			return false;  
		}
		if(input<1 || input>99) {
			ui.ShowMessageBox("ERROR", "Points must be in range 1-99", JOptionPane.ERROR_MESSAGE);
			return false;
		}
		if (table.getSelectedRowCount() != 1) {
			ui.ShowMessageBox("ERROR", "Please select one question from the list", JOptionPane.ERROR_MESSAGE);
			return false;
		}
		return true;
	}

}
